#!/usr/bin/env python3
"""
智慧医院资源调度与预约优化平台启动脚本
"""

import os
import sys
import subprocess
from pathlib import Path

def check_requirements():
    """检查系统要求"""
    print("🔍 检查系统要求...")
    
    # 检查Python版本
    if sys.version_info < (3, 11):
        print("❌ Python版本需要3.11或更高")
        return False
    
    # 检查必要的包
    required_packages = [
        'flask', 'flask_sqlalchemy', 'flask_cors', 'flask_jwt_extended',
        'celery', 'redis', 'psycopg2', 'numpy', 'scipy', 'tensorflow',
        'deap', 'pandas', 'matplotlib', 'seaborn', 'plotly'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ 缺少必要的包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    
    print("✅ 系统要求检查通过")
    return True

def setup_environment():
    """设置环境变量"""
    print("🔧 设置环境变量...")
    
    # 设置默认环境变量
    env_vars = {
        'SECRET_KEY': 'dev-secret-key-change-in-production',
        'DATABASE_URL': 'postgresql://postgres:postgres@localhost/hospital_scheduler',
        'REDIS_URL': 'redis://localhost:6379/0',
        'CELERY_BROKER_URL': 'redis://localhost:6379/1',
        'CELERY_RESULT_BACKEND': 'redis://localhost:6379/1'
    }
    
    for key, value in env_vars.items():
        if key not in os.environ:
            os.environ[key] = value
            print(f"  {key} = {value}")
    
    print("✅ 环境变量设置完成")

def start_services():
    """启动服务"""
    print("🚀 启动智慧医院资源调度系统...")
    
    try:
        # 导入并启动应用
        from app import create_app, db
        from app.models import User, Department, Resource
        
        app = create_app()
        
        with app.app_context():
            # 初始化数据库
            print("📊 初始化数据库...")
            db.create_all()
            
            # 创建默认数据
            if not User.query.filter_by(username='admin').first():
                from werkzeug.security import generate_password_hash
                admin = User(
                    username='admin',
                    email='admin@hospital.com',
                    password_hash=generate_password_hash('admin123'),
                    role='admin',
                    phone='13800138000'
                )
                db.session.add(admin)
                print("  ✅ 创建默认管理员用户 (admin/admin123)")
            
            if not Department.query.first():
                departments = [
                    {'name': '内科', 'description': '内科疾病诊疗'},
                    {'name': '外科', 'description': '外科手术诊疗'},
                    {'name': '妇科', 'description': '妇科疾病诊疗'},
                    {'name': '儿科', 'description': '儿童疾病诊疗'},
                    {'name': '急诊科', 'description': '急诊诊疗'},
                ]
                
                for dept_data in departments:
                    department = Department(**dept_data)
                    db.session.add(department)
                print("  ✅ 创建默认科室数据")
            
            if not Resource.query.first():
                resources = [
                    {'name': '内科诊室1', 'resource_type': 'consultation_room', 'department_id': 1, 'capacity': 1, 'location': '1楼101'},
                    {'name': '内科诊室2', 'resource_type': 'consultation_room', 'department_id': 1, 'capacity': 1, 'location': '1楼102'},
                    {'name': '外科手术室1', 'resource_type': 'operating_room', 'department_id': 2, 'capacity': 1, 'location': '2楼201'},
                    {'name': '外科手术室2', 'resource_type': 'operating_room', 'department_id': 2, 'capacity': 1, 'location': '2楼202'},
                    {'name': 'CT检查室', 'resource_type': 'equipment', 'department_id': 1, 'capacity': 1, 'location': '1楼103'},
                    {'name': 'MRI检查室', 'resource_type': 'equipment', 'department_id': 1, 'capacity': 1, 'location': '1楼104'},
                ]
                
                for resource_data in resources:
                    resource = Resource(**resource_data)
                    db.session.add(resource)
                print("  ✅ 创建默认资源数据")
            
            db.session.commit()
        
        print("🌐 启动Web服务器...")
        print("  📱 Web管理端: http://localhost:5000")
        print("  🔗 API接口: http://localhost:5000/api")
        print("  📊 仪表盘: http://localhost:5000/dashboard")
        print("  📋 预约管理: http://localhost:5000/appointments")
        print("  🏥 资源管理: http://localhost:5000/resources")
        print("  ⚙️ 调度管理: http://localhost:5000/scheduling")
        print("  📈 数据分析: http://localhost:5000/analytics")
        print("\n💡 默认管理员账号: admin / admin123")
        print("🔄 按 Ctrl+C 停止服务")
        
        # 启动Flask应用
        app.run(
            host='0.0.0.0',
            port=5000,
            debug=True
        )
        
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        return False

def main():
    """主函数"""
    print("🏥 智慧医院资源调度与预约优化平台")
    print("=" * 50)
    
    # 检查系统要求
    if not check_requirements():
        sys.exit(1)
    
    # 设置环境
    setup_environment()
    
    # 启动服务
    start_services()

if __name__ == '__main__':
    main()
